#include "Data.h"

#include <cassert>
//#include <iostream> //for debug

#include "memdb/impl/simple/KvTable.h"

namespace memdb {
namespace impl {
namespace simple {

Data::Data(const std::filesystem::path & dbpath, const std::string & name)
: _dbpath(dbpath)
, _dir(_dbpath/ "data")
, _name(name)
, _table(new KvTable(_dir, _name))
{
	open();
}
Data::~Data(){
	close();
}

std::error_code Data::open() {
	return _table->open();
}
std::error_code Data::close() {
	return _table->close();
}
bool Data::isOpened() const {
	return _table->isOpened();
}

std::error_code Data::destroy(){
	if(isOpened()){ //closed first
		if(auto && ec = close();ec){
			return ec;
		}
	}

	if(auto && ec = _table->destroy(); ec){
		return ec;
	}
	std::filesystem::remove_all(_dir);
	return std::error_code();
}
bool Data::exists() const{
	return _table->exists();
}
const std::string & Data::name() const {
	return _name;
}


//dml - shortcut interface 
std::error_code Data::insert(const std::string & key, const std::string & value){
	return _table->records().insert(key, value);
}
std::error_code Data::replace(const std::string & key, const std::string & value){
	return _table->records().replace(key, value);
}

std::error_code Data::remove(const std::string & key){
	return _table->records().remove(key);
}
std::error_code Data::update(const std::string & key, const std::string & value){
	return _table->records().update(key, value);
}

//dql - shortcut interface 
bool Data::exists(const std::string & key) const {
	return _table->records().exists(key);
}
std::error_code Data::get(const std::string & key, std::string & value) const{
	return _table->records().get(key, value);
}

size_t Data::count() const{
	return _table->records().count();
}

using IteratorType = helper::iter::Iterator<Data::Item>;
std::unique_ptr<IteratorType> Data::iterator() const {
	return _table->records().iterator();
}
std::unique_ptr<IteratorType> Data::iterator(size_t offset, size_t len) const{
	return _table->records().iterator(offset, len);
}
std::unique_ptr<IteratorType> Data::iterator(const std::string &key, size_t offset, size_t len) const{
	return _table->records().iterator(key, offset, len);
}

}//namespace simple
}//namespace impl
}//namespace memdb
